package com.erpanderp.wam.util;

import java.util.Map;
import java.util.Set;

import javax.el.ELContext;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.erpanderp.wam.adm.view.UserMenuBean;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.view.user.LoginBean;

public class WAMPhaseListener implements PhaseListener {
	
	public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

    public void beforePhase(PhaseEvent event) {
    }

    public void afterPhase(PhaseEvent event) {
        FacesContext fc = event.getFacesContext();
        boolean loginPage = fc.getViewRoot().getViewId().lastIndexOf("login") > -1 ? true : false;
       
        System.out.println("Request Map: " + fc.getExternalContext().getRequestParameterMap());
        
        if (!loginPage 
        		&& !loggedIn() 
        		&& (fc.getExternalContext().getRequestParameterMap() == null || fc.getExternalContext().getRequestParameterMap().size() == 0)
        		&& !fc.getViewRoot().getViewId().contains("aboutWAM")
        		&& !fc.getViewRoot().getViewId().contains("timesheetscronjob")
        		&& !fc.getViewRoot().getViewId().contains("timesheetsubmissionremainder")
        		&& !fc.getViewRoot().getViewId().contains("unapprovedtimesheetreminder")
        		&& !fc.getViewRoot().getViewId().contains("leavescronjob")
        		&& !fc.getViewRoot().getViewId().contains("eform")
        		&& !fc.getViewRoot().getViewId().contains("birthdaywishescronjob")
        		) {
    
        	NavigationHandler nh = fc.getApplication().getNavigationHandler();
            nh.handleNavigation(fc, null, "login");
        }
    }

    private boolean loggedIn() {
        return LoginBean.isLoggedIn();
    }

}
